extends CanvasLayer

@onready var mush_room_1: StaticBody2D = %MushRoom1
@onready var mush_room_2: StaticBody2D = %MushRoom2
@onready var mush_room_3: StaticBody2D = %MushRoom3
@onready var goblin_1: StaticBody2D = %Goblin1
@onready var goblin_2: StaticBody2D = %Goblin2
@onready var goblin_3: StaticBody2D = %Goblin3
@onready var players: Array = [mush_room_1, mush_room_2, mush_room_3]
@onready var enemies: Array = [goblin_1, goblin_2, goblin_3]
@onready var battle_victory_defeat: CanvasLayer = $BattleVictoryDefeat

var small_turn_count: int = 0
var turn_count: int = 0
const NULL_POSITION: int = -1

func _ready() -> void:
	await get_tree().create_timer(1).timeout
	Engine.time_scale = 3
	Events.signal_player_turn.connect(_player_turn)
	Events.signal_enemy_turn.connect(_enemy_turn)
	_player_turn()

func _process(_delta: float) -> void:
	victory_or_defeat(players, enemies)

func _player_turn() -> void:
	if small_turn_count == players.size() + enemies.size():
		reset_is_current_turn_played(players, enemies)
		small_turn_count = 0
	var player: StaticBody2D = get_current_play_sprites(players)
	small_turn_count += 1
	if player != null:
		player.turn(players, enemies)
	else:
		_enemy_turn()
		
func _enemy_turn() -> void:
	if small_turn_count == players.size() + enemies.size():
		reset_is_current_turn_played(players, enemies)
		small_turn_count = 0
	var enemy: StaticBody2D = get_current_play_sprites(enemies)
	small_turn_count += 1
	if enemy != null:
		enemy.turn(players, enemies)
	else: 
		_player_turn() 

func get_current_play_sprites(array: Array) -> StaticBody2D:
	var valid_sprites := []
	# 过滤出符合条件的精灵
	for sprite in array:
		if sprite.health > 0 && !sprite.is_current_turn_played:
			valid_sprites.append(sprite)
	# 如果没有符合条件的精灵，返回 null
	if valid_sprites.size() == 0:
		return null
	# 冒泡排序：按 physical_position 从小到大排序
	for i in range(valid_sprites.size()):
		for j in range(0, valid_sprites.size() - i - 1):
			if valid_sprites[j].physical_location > valid_sprites[j + 1].physical_location:
				var temp: StaticBody2D = valid_sprites[j]
				valid_sprites[j] = valid_sprites[j + 1]
				valid_sprites[j + 1] = temp
	# 返回第一个元素（physical_position 最小）
	return valid_sprites[0]
	
func reset_is_current_turn_played(reset_players: Array, reset_enemies: Array) -> void:
	var all_acted := true
	# 检查 player 组
	for sprite in reset_players:
		if !sprite.is_current_turn_played and sprite.health > 0:
			all_acted = false
			break  # 只要有一个没出手，就不用继续检查了
	# 如果 player 中还有未出手的，就不检查敌人了
	if !all_acted:
		return
	# 检查 enemies 组
	for sprite in reset_enemies:
		if !sprite.is_current_turn_played and sprite.health > 0:
			all_acted = false
			break
	# 如果全部都出手了，就重置 is_current_turn_played
	if all_acted:
		for sprite in reset_players:
			sprite.is_current_turn_played = false
		for sprite in reset_enemies:
			sprite.is_current_turn_played = false
	
func victory_or_defeat(vod_players: Array, vod_enemies: Array) -> void:
	var all_players_dead := true
	for player in vod_players:
		if player.health > 0:
			all_players_dead = false
			break
	var all_enemies_dead := true
	for enemy in vod_enemies:
		if enemy.health > 0:
			all_enemies_dead = false
			break
	if all_players_dead:
		print("Defeat！")
		kill_game()
	
	elif all_enemies_dead:
		print("Victory！")
		kill_game()
		
func kill_game():
	queue_free()
	battle_victory_defeat.visible = true
	
	
